
package com.cyanite.playlv2.blog;

import com.cyanite.playlv2.preferences.Preferences;
import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.ServiceException;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;

public class DoubanBlogManager {
    public static String API_KEY = "01a1cbc77be911d104e5635673bb3573";
    public static String SECRET = "182231c2ee326208";
    public static String CALLBACK = "com.cyanite.playlv2://BlogBindActivity";
    private Context mCxt;
    private DoubanService mService;

    public DoubanBlogManager(Context mCxt) {
        super();
        this.mCxt = mCxt;
        mService = new DoubanService("playtrip_douban_blog", API_KEY, SECRET, false);
    }

    public void bind() {
        String url = mService.getAuthorizationUrl(CALLBACK);
        Preferences.saveDoubanRequestTokenPair(mCxt, mService.getRequestToken(), mService.getRequestTokenSecret());
        mCxt.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    public Boolean handleAuthCallBack() {
        mService.setRequestToken(Preferences.readDoubanRequestToken(mCxt));
        mService.setRequestTokenSecret(Preferences.readDoubanRequestTokenSecret(mCxt));

        ArrayList<String> list = mService.getAccessToken();
        if (list == null)
            return false;
        else {
            Preferences.saveDoubanAccessTokenPair(mCxt, list.get(0), list.get(1));
            Toast.makeText(mCxt, "绑定豆瓣微博成功", Toast.LENGTH_LONG).show();
            return true;
        }
    }

    public void sendToDoubanGuangbo(String blogContent) {
        if (Preferences.readDoubanAccessToken(mCxt).equals("")) {
            Toast.makeText(mCxt, "requiring token missed, please bind sina blog first!",
                    Toast.LENGTH_LONG).show();
            return;
        }
        mService.setAccessToken(Preferences.readDoubanAccessToken(mCxt), Preferences.readDoubanAccessTokenSecret(mCxt));
        try {
            mService.createSaying(new PlainTextConstruct(blogContent));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
}
